app.controller("areaCtrl", ["$scope", "$http", "$filter", "$rootScope", "$stateParams", "$timeout", "$modal", "lodash",
function($scope, $http, $filter, $rootScope, $stateParams, $timeout, $modal, lodash) {
    $rootScope.initBreadcrumb($scope.breadcrumb);
    $rootScope.initHeaderElements($scope.settings);
    $scope.breadcrumb.push('区域管理');

    $scope.settings.searchEle = {
        show: true, //显示查询框
        func: function (keyword) {
            seachArea(keyword);
        },
        blurFunc: function (keyword) {
            seachArea(keyword);
        }
    };
    var addArea = {
        show: $rootScope.isMatrixRole(),
        label: "新建区域",
        func: function () {
            addAreaItem();
        }
    };
    $scope.settings.btnEle.push(addArea);

    $scope.info = {
        // 原始区域数据
        originAreaArray: [
            {"id": "1", "code": "gzidc", "parentCode": "-", "desc": "广州数据中心", "status": "on"},
            {"id": "2", "code": "usaws", "parentCode": "-", "desc": "美国数据中心", "status": "on"},
            {"id": "3", "code": "auaws", "parentCode": "-", "desc": "澳洲数据中心", "status": "on"},
            {"id": "4", "code": "euaws", "parentCode": "-", "desc": "欧洲数据中心", "status": "off"},
            {"id": "5", "code": "ukls", "parentCode": "euaws", "desc": "英国ls仓库", "status": "off"}
        ],
        areaList: [],
    };

    //设置data-table
    $scope.options = {
        rowHeight: 40,
        headerHeight: 40,
        footerHeight: 50,
        columnMode: 'force',
        forceFillColumns: true,
        emptyMessage: '暂无数据！',
        columns: [
            { name: "区域代号", width: 100,
                cellRenderer: function () {
                    return '<a href="javascript:void(0);" ng-click="updateAreaItem($row)">{{$row.code}}</a>';
                }
            },
            { name: "上级区域代号", width: 100, prop: 'parentCode'},
            { name: "说明", width: 80, prop: 'desc'},
            {
                name: "配置",
                width: 100,
                cellRenderer: function () {
                    return '<a href="javascript:void(0);" ng-click="switchStatus($row)">{{$row.status == "on" ? "禁用" : "启用"}}</a>';
                }
            }
        ],
    };

    setTableData();

    // 获取区域数据
    function setTableData() {
        $timeout(function() {
            $scope.tableData = $scope.info.originAreaArray;
        }, 200);
    }

    // 切换状态
    $scope.switchStatus = function(row) {
        var confirm = {
            titleData: "提示",
            bodyData: "确定要切换状态吗？"
        };
        $rootScope.confirmWindow(confirm, function (data) {
            if(data){
                row.status = row.status == "on" ? "off" : "on";
                $rootScope.toasterSuccessInfo("状态切换成功！");
            }
        })
    };

    // 查询区域数据
    function seachArea(keyword) {
        var searchAreaData = new Array();
        angular.forEach($scope.info.originAreaArray, function(item) {
            if(item.code == keyword || item.parentCode == keyword || item.desc == keyword) {
                searchAreaData.push(item);
            }
        });
        $scope.tableData = searchAreaData.length ? searchAreaData : $scope.info.originAreaArray;
    };

    // 添加
    function addAreaItem() {
        openModal("add");
    };
    
    // 修改
    $scope.updateAreaItem = function(row) {
        openModal("update", row);
    };

    // 打开modal
    function openModal(type, row) {
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/ucloud2.0/tpl/areaModal.html"),
            controller: "areaModalCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                type: function () {
                    return type;
                },
                row: function() {
                    return row;
                },
                data: function() {
                    return $scope.info.originAreaArray;
                }
            }
        });

        modalInstance.result.then(function (areaItem) {
            ajaxFun(areaItem);
        }, function (reason) {
            console.log("关闭modal");
        });
    };
        
    // 更新数据
    function ajaxFun(areaItem) {
        if(!areaItem.id) {
            // 新增
            areaItem.id = $scope.info.originAreaArray.length + 1;
            areaItem.status = "off";
            $scope.info.originAreaArray.push(areaItem);
            $scope.tableData = $scope.info.originAreaArray;
        } else {
            // 修改
            var updateAreaItem = lodash.findWhere($scope.info.originAreaArray, {id: areaItem.id});
            updateAreaItem.code = areaItem.code;
            updateAreaItem.parentCode = areaItem.parentCode;
            updateAreaItem.desc = areaItem.desc;
        }
        $rootScope.toasterSuccessInfo("操作成功！");
    };

}]);

app.controller("areaModalCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "lodash", "type", "row", "data", function ($scope, $rootScope, $modalInstance, $http, lodash, type, row, data) {
    $scope.info = {
        title: type == "add" ? "添加区域" : "修改区域",
        parentAreaList: [],
        sltparentAreaItem: '',
        code: row ? row.code : '',
        parentCode: '',
        desc: row ? row.desc : ''
    }

    setParentAreaList();

    // 设置区域数据（显示上级区域名称）
    function setParentAreaList() {
        var areaModalList = angular.copy(data);
        angular.forEach(areaModalList, function(d) {
            d.crtname = d.desc;
        });
        if(type != "add") {
            lodash.remove(areaModalList, {id: row.id});
            $scope.info.sltparentAreaItem = lodash.findWhere(areaModalList, {code: row.parentCode});
        }
        $scope.info.parentAreaList = areaModalList;
    };

    $scope.createClick = function () {
        if(!$scope.info.code) {
            $rootScope.toasterWarningInfo("区域代码不能为空！");
            return false;
        }
        if(type == "add") {
            if(lodash.findIndex(data, {code: $scope.info.code}) != -1) {
                $rootScope.toasterWarningInfo("区域代码不能重复！");
                return false;
            }
        }
        if(!$scope.info.sltparentAreaItem.id) {
            $rootScope.toasterWarningInfo("上级区域不能为空！");
            return false;
        }
        if(!$scope.info.desc) {
            $rootScope.toasterWarningInfo("区域说明不能为空！");
            return false;
        }
        var areaItem = {
            "code": $scope.info.code,
            "parentCode": $scope.info.sltparentAreaItem.code,
            "desc": $scope.info.desc
        };
        if(type != "add") {
            areaItem.id = row.id;
        }
        $modalInstance.close(areaItem);
    };

    $scope.cancelClick = function () {
        $modalInstance.dismiss("cancel");
    };
}]);
